package com.hebtu.helper.modules.user.controller;

import com.hebtu.helper.common.constants.LoginMessage;
import com.hebtu.helper.common.exception.HelperException;
import com.hebtu.helper.common.utils.H;
import com.hebtu.helper.common.utils.MyHttp;
import com.hebtu.helper.modules.user.entity.UserEntity;
import com.hebtu.helper.modules.user.service.UserService;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * 用户接口
 * @author YKF
 * @date 2019/6/19 14:04
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     *课表查询
     * @param username  学号
     * @param password  明文密码
     * @param xnm  学年
     * @param xqm  学期
     * @return
     */
    @RequestMapping("/kbcx")
    public StringBuffer queryKb(String username,String password,String xnm,String xqm){
        MyHttp myHttp=(MyHttp) postMessage(username,password,false);
        if(myHttp==null)
            throw new HelperException( "请先登陆");
        ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("xnm", xnm));//学年
        params.add(new BasicNameValuePair("xqm", xqm));//学期
        StringBuffer sb=null;
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");    //封装成参数对象
            sb = myHttp.sendPostRequest(LoginMessage.KBCX, entity);//发送请求
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb;
    }

    /**
     * 用户登陆
     * @param username  学号
     * @param password  明文密码
     * @return
     */
    @RequestMapping("/login")
    public H login(String username, String password) {
        UserEntity user=(UserEntity) postMessage(username, password,true);

        return H.success("登陆成功").put("data",user);
    }


    /**
     * 登陆
     * @param username   学号
     * @param password   密码
     * @return  http信息，重定向
     */
    private Object postMessage(String username,String password,boolean isFindMeg){
        MyHttp myHttp = new MyHttp();
        StringBuffer privateKey=myHttp.getPublicKey();
        String newPassword = myHttp.getPasswordJson(password, privateKey); //加密后的密码
        ArrayList<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("csrftoken", myHttp.getCsrftoken()));//csrftoken，不可缺少这个参数
        params.add(new BasicNameValuePair("yhm",username));//学号
        params.add(new BasicNameValuePair("mm", newPassword));//密码
        params.add(new BasicNameValuePair("mm", newPassword));//密码
        try {
            UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");	//封装成参数对象
            StringBuffer sb=myHttp.sendPostRequest(LoginMessage.LOGIN_URL, entity);//发送请求
            String html=sb.toString();
            //检测是否有登陆错误的信息，有则记录信息，否则登陆成功
            if(html.contains(LoginMessage.CHECK_ERROR)){
                throw new HelperException(LoginMessage.CHECK_ERROR);
            }else if(html.contains(LoginMessage.USER_NULL_ERROR)){
                throw new HelperException(LoginMessage.USER_NULL_ERROR);
            }else if(html.contains(LoginMessage.PASSWORD_NULL_ERROR)){
                throw new HelperException(LoginMessage.PASSWORD_NULL_ERROR);
            }else {
                if(isFindMeg)
                    return userMessage(myHttp,password);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return myHttp;
    }


    /**
     * 获取用户信息
     * @param myHttp
     */
    private UserEntity userMessage(MyHttp myHttp,String pwd){
        UserEntity user=null;
        String myMsg= String.valueOf(myHttp.sendGetRequest(LoginMessage.MYSELF));
        JSONObject jMyMsg = null;
        try {
            jMyMsg  = new JSONObject (myMsg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            String stNo=jMyMsg.getString("xh");
            user = userService.selectByStNo(stNo);
            if(user!=null){
                user.setPassword(pwd);
                return user;
            }
            user = new UserEntity();
            user.setStNo(stNo);
            user.setName(jMyMsg.getString("xm"));
            user.setSex(jMyMsg.getString("xbm"));
            user.setJgId(jMyMsg.getString("jg_id"));
            user.setBhId(jMyMsg.getString("bh_id"));
            userService.insert(user);
            user.setPassword(pwd);
        } catch (JSONException e) {
            user=null;
            e.printStackTrace();
        }
        return user;
    }
}
